//
//  ViewController.m
//  DrawRouteOnMap
//
//  Created by Uniy Xu on 12-9-3.
//  Copyright (c) 2012年 Uniy Xu. All rights reserved.
//

#import "ViewController.h"
#import "AFHTTPClient.h"
#import "AFJSONRequestOperation.h"

@interface ViewController ()

@property (nonatomic, retain) NSMutableArray *_path;
@property (nonatomic, retain) MKMapView *_mapView;
- (void)setRouteWithStartCoordinate2D:(CLLocationCoordinate2D)startCoordinate2D
                      endCoordinate2D:(CLLocationCoordinate2D)endCoordinate2D;
- (void)parseResponse:(NSDictionary *)response;
- (NSMutableArray *)decodePolyLine:(NSString *)encodedStr;
@end

@implementation ViewController
@synthesize _mapView;
@synthesize _path;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    _mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
    _mapView.showsUserLocation = YES;
    _mapView.delegate = self;
    [self.view addSubview:_mapView];
    
    /*
    MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(self. location.coordinate, REGION_SIZE, REGION_SIZE);
    MKCoordinateRegion adjustedRegion = [_mapView regionThatFits:viewRegion]; [_mapView setRegion:adjustedRegion animated:NO];
     */
    // 31.2121190 , 121.5437160
    // 31.22323799999999 , 121.4455210
    
    [_mapView setRegion:MKCoordinateRegionMake(CLLocationCoordinate2DMake(31.2121190, 121.5437160), MKCoordinateSpanMake(0.05, 0.05)) animated:NO];
    
    [self setRouteWithStartCoordinate2D:CLLocationCoordinate2DMake(31.2121190, 121.5437160)
                        endCoordinate2D:CLLocationCoordinate2DMake(31.22323799999999, 121.4455210)];
}

- (void)setRouteWithStartCoordinate2D:(CLLocationCoordinate2D)startCoordinate2D
                      endCoordinate2D:(CLLocationCoordinate2D)endCoordinate2D
{
    AFHTTPClient *_httpClient = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://maps.googleapis.com/"]];
    [_httpClient registerHTTPOperationClass: [AFJSONRequestOperation class]];
    [_httpClient setDefaultHeader:@"Accept" value:@"application/json"];
    
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
    [parameters setObject:[NSString stringWithFormat:@"%f,%f", startCoordinate2D.latitude, startCoordinate2D.longitude] forKey:@"origin"];
    [parameters setObject:[NSString stringWithFormat:@"%f,%f", endCoordinate2D.latitude, endCoordinate2D.longitude] forKey:@"destination"];
    [parameters setObject:@"true" forKey:@"sensor"];
    
    NSMutableURLRequest *request = [_httpClient requestWithMethod:@"GET" path: @"maps/api/directions/json" parameters:parameters];
    request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    
    AFHTTPRequestOperation *operation = [_httpClient HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id response) {
        NSInteger statusCode = operation.response.statusCode;
        if (statusCode == 200) {
            [self parseResponse:response];
            
        } else {
            
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { }];
    
    [_httpClient enqueueHTTPRequestOperation:operation];
}

- (void)parseResponse:(NSDictionary *)response
{
    NSArray *routes = [response objectForKey:@"routes"];
    NSDictionary *route = [routes lastObject];
    if (route) {
        NSString *overviewPolyline = [[route objectForKey: @"overview_polyline"] objectForKey:@"points"];
        _path = [self decodePolyLine:overviewPolyline];
        if ([_path count] > 0) {
            NSInteger numberOfSteps = _path.count;
            
            CLLocationCoordinate2D coordinates[numberOfSteps];
            for (NSInteger index = 0; index < numberOfSteps; index++) {
                CLLocation *location = [_path objectAtIndex:index];
                CLLocationCoordinate2D coordinate = location.coordinate;
                
                coordinates[index] = coordinate;
            }
            
            MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps];
            [_mapView addOverlay:polyLine];
        }
    }
}

- (NSMutableArray *)decodePolyLine:(NSString *)encodedStr
{
    NSMutableString *encoded = [[NSMutableString alloc] initWithCapacity:[encodedStr length]];
    [encoded appendString:encodedStr];
    [encoded replaceOccurrencesOfString:@"\\\\" withString:@"\\"
                                options:NSLiteralSearch
                                  range:NSMakeRange(0, [encoded length])];
    NSInteger len = [encoded length];
    NSInteger index = 0;
    NSMutableArray *array = [[NSMutableArray alloc] init];
    NSInteger lat=0;
    NSInteger lng=0;
    while (index < len) {
        NSInteger b;
        NSInteger shift = 0;
        NSInteger result = 0;
        do {
            b = [encoded characterAtIndex:index++] - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lat += dlat;
        shift = 0;
        result = 0;
        do {
            b = [encoded characterAtIndex:index++] - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lng += dlng;
        NSNumber *latitude = [[NSNumber alloc] initWithFloat:lat * 1e-5];
        NSNumber *longitude = [[NSNumber alloc] initWithFloat:lng * 1e-5];
        
        CLLocation *location = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]];
        [array addObject:location];
    }
    
    return array;
}

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
    MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:overlay];
    polylineView.strokeColor = [UIColor blueColor];
    polylineView.lineWidth = 3.0;
    
    return polylineView;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    [self set_mapView:nil];
    [self set_path:nil];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void)dealloc
{
    [super dealloc];
    [_mapView release];
    [_path release];
}

@end
